package com.cgbl.service.im.page;

import static com.netease.yunxin.kit.chatkit.ui.ChatKitUIConstant.LIB_TAG;
import static com.netease.yunxin.kit.corekit.im.utils.RouterConstant.KEY_REQUEST_SELECTOR_NAME;
import static com.netease.yunxin.kit.corekit.im.utils.RouterConstant.REQUEST_CONTACT_SELECTOR_KEY;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import com.cgbl.service.databinding.CustomChatSettingActivityBinding;
import com.gyf.immersionbar.ImmersionBar;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.StickTopSessionInfo;
import com.netease.nimlib.sdk.team.model.CreateTeamResult;
import com.netease.nimlib.sdk.team.model.Team;
import com.netease.yunxin.kit.alog.ALog;
import com.netease.yunxin.kit.chatkit.repo.ChatRepo;
import com.netease.yunxin.kit.chatkit.ui.R;
import com.netease.yunxin.kit.chatkit.ui.common.ChatCallback;
import com.netease.yunxin.kit.chatkit.ui.page.ChatSearchActivity;
import com.netease.yunxin.kit.chatkit.ui.page.ChatTeamActivity;
import com.netease.yunxin.kit.chatkit.ui.page.viewmodel.ChatSettingViewModel;
import com.netease.yunxin.kit.common.ui.activities.BaseActivity;
import com.netease.yunxin.kit.common.ui.utils.AvatarColor;
import com.netease.yunxin.kit.common.ui.viewmodel.LoadStatus;
import com.netease.yunxin.kit.contactkit.repo.ContactRepo;
import com.netease.yunxin.kit.contactkit.ui.userinfo.CommentActivity;
import com.netease.yunxin.kit.corekit.im.model.FriendInfo;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.provider.FetchCallback;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.kit.teamkit.ui.activity.TeamSettingActivity;

import java.util.ArrayList;

public class CustomChatSettingActivity extends BaseActivity {
    private static final String TAG = "ChatSettingActivity";

    CustomChatSettingActivityBinding binding;

    ChatSettingViewModel viewModel;

    UserInfo userInfo;
    String accId;

    FriendInfo friendInfo;

    private ActivityResultLauncher<Intent> launcher;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).transparentStatusBar().statusBarDarkFont(true).init();
        binding = CustomChatSettingActivityBinding.inflate(getLayoutInflater());
        viewModel = new ViewModelProvider(this).get(ChatSettingViewModel.class);
        setContentView(binding.getRoot());
//        binding.title.setOnBackIconClickListener(v -> onBackPressed()).setTitle(R.string.chat_setting);
        initView();
        initTiterBar();
        initData();
    }

    private void initTiterBar() {
        TextView titleView = findViewById(R.id.tv_title);
        ImageView backView = findViewById(R.id.iv_back);
        titleView.setText("聊天设置");
        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }


    private void initView() {
        userInfo = (UserInfo) getIntent().getSerializableExtra(RouterConstant.CHAT_KRY);
        accId = (String) getIntent().getSerializableExtra(RouterConstant.CHAT_ID_KRY);
        friendInfo = ContactRepo.getFriend(accId);
        if (userInfo == null && TextUtils.isEmpty(accId)) {
            finish();
            return;
        }
        if (TextUtils.isEmpty(accId)) {
            accId = userInfo.getAccount();
        }
        refreshView();
        binding.ivAdd.setOnClickListener(v -> selectUsersCreateGroup());
        String finalAccId = accId;
        launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() != RESULT_OK) {
                return;
            }
            ALog.d(LIB_TAG, TAG, "contact selector result");
            Intent data = result.getData();
            if (data != null) {
                String comment = result.getData().getStringExtra(CommentActivity.REQUEST_COMMENT_NAME_KEY);
                friendInfo.setAlias(comment);
                ContactRepo.updateAlias(accId, comment);
                ArrayList<String> friends = data.getStringArrayListExtra(REQUEST_CONTACT_SELECTOR_KEY);
                if (friends != null && !friends.isEmpty()) {
                    friends.add(finalAccId);
                    XKitRouter.withKey(RouterConstant.PATH_CREATE_NORMAL_TEAM_ACTION).withParam(REQUEST_CONTACT_SELECTOR_KEY, friends).withParam(KEY_REQUEST_SELECTOR_NAME, data.getStringArrayListExtra(KEY_REQUEST_SELECTOR_NAME)).navigate(res -> {
                        if (res.getSuccess() && res.getValue() instanceof CreateTeamResult) {
                            Team teamInfo = ((CreateTeamResult) res.getValue()).getTeam();
                            Intent intent = new Intent(CustomChatSettingActivity.this, ChatTeamActivity.class);
                            intent.putExtra(RouterConstant.CHAT_KRY, teamInfo);
                            startActivity(intent);
                            finish();
                        }
                    });
                }
            }
        });
    }

    private void refreshView() {
        if (userInfo == null) {
            binding.avatar.setData(null, accId, AvatarColor.avatarColor(accId));
            binding.tvName.setText(accId);
        } else {
            String name = TextUtils.isEmpty(friendInfo.getAlias()) ? userInfo.getName() : friendInfo.getAlias();
            if (name == null) {
                name = userInfo.getAccount();
            }
            ALog.d(LIB_TAG, TAG, "initView name -->> " + name);
            binding.avatar.setData(userInfo.getAvatar(), name, AvatarColor.avatarColor(userInfo.getAccount()));
            binding.tvName.setText(name);
        }
    }

    private void initData() {
        if (accId == null) return;
        viewModel.getUserInfoLiveData().observe(this, result -> {
            if (result.getLoadStatus() == LoadStatus.Success) {
                userInfo = result.getData();
                refreshView();
            }
        });
        viewModel.getUserInfo(accId);
        binding.scSessionTop.setChecked(ChatRepo.isStickTop(accId));
        binding.scSessionTop.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                if (!checked) {
                    ChatRepo.addStickTop(accId, new ChatCallback<StickTopSessionInfo>() {
                        @Override
                        public void onSuccess(@Nullable StickTopSessionInfo param) {
                            binding.scSessionTop.setChecked(true);
                            ChatRepo.notifyP2PStickTop(accId);
                        }
                    });
                } else {
                    ChatRepo.removeStickTop(accId, new ChatCallback<Void>() {
                        @Override
                        public void onSuccess(@Nullable Void param) {
                            binding.scSessionTop.setChecked(false);
                            ChatRepo.notifyP2PStickTop(accId);
                        }
                    });
                }
            }
        });

        binding.scMessageNotice.setChecked(!ChatRepo.isNeedNotify(accId));
        binding.scMessageNotice.setOnCheckedChangeListener((compoundButton, checked) -> ChatRepo.setNotify(accId, !checked, new ChatCallback<Void>() {
            @Override
            public void onSuccess(@Nullable Void param) {
                binding.scMessageNotice.setChecked(checked);
            }
        }));
        binding.remark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (userInfo == null || friendInfo == null) {
                    return;
                }
                Intent intent = new Intent();
                intent.setClass(CustomChatSettingActivity.this, CommentActivity.class);
                intent.putExtra(CommentActivity.REQUEST_COMMENT_NAME_KEY, friendInfo.getAlias());
                launcher.launch(intent);
            }
        });
        binding.search.setOnClickListener(view -> XKitRouter.withKey(RouterConstant.PATH_CHAT_SEARCH_PAGE)
                .withParam(RouterConstant.KEY_SESSION_TYPE, "p2p")
                .withParam(RouterConstant.CHAT_KRY, accId)
                .withContext(CustomChatSettingActivity.this).navigate());
    }

    private void selectUsersCreateGroup() {
        ArrayList<String> filterList = new ArrayList<>();
        filterList.add(accId);
        XKitRouter.withKey(RouterConstant.PATH_CONTACT_SELECTOR_PAGE).withParam(RouterConstant.KEY_CONTACT_SELECTOR_MAX_COUNT, 199).withParam(RouterConstant.KEY_REQUEST_SELECTOR_NAME_ENABLE, true).withContext(this).withParam(RouterConstant.SELECTOR_CONTACT_FILTER_KEY, filterList).navigate(launcher);
    }
}
